/**
 * Created by wangcan on 2017-10-26.
 */
var async = require('async');
var moment = require('moment');
var schedule = require("node-schedule");
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var mtOrder = mongoose.model('mtOrder');
var User = mongoose.model('user');
var Regions = mongoose.model('masterData_Regions');
var Community = mongoose.model('community');
var userService = require('./../userService');
var Question = mongoose.model('question');
var Goods = mongoose.model('goods');
var UserInvitation = mongoose.model('user_invitation');

// 查询订单总佣金
exports.orderTatolCommisionList = function (body, size, index, callback){

    var parallelLimitCount = 6; // 限制并行个数
    var dateArr = [];
    var dateArrCount = 0;

    var startDate = null;
    var endDate = null;
    if (body.startdate && body.enddate) {
        if (size == -1) {
            dateArr = toolUtil.getArrayDateByStartEndDateMin(body.startdate, body.enddate);
            dateArrCount = dateArr.length;
        } else {
            var startDateSelect = body.startdate;
            var endDateSelect = body.enddate;
            var startDateTemp = null;
            var endDateTemp = moment(endDateSelect, "YYYY-MM-DD").add(-index, 'days').format();
            dateArrCount = ((new Date(endDateSelect).getTime() - new Date(startDateSelect).getTime()) / 86400000) + 1;
            // dateArrCount = toolUtil.getArrayDateByStartEndDateMin(body.startdate, body.enddate);

            dateArr = toolUtil.getArrayDateByStartEndDateMin(body.startdate, endDateTemp);
            if (dateArr != null && dateArr.length > 0) {
                if (dateArr.length > size) {
                    startDateTemp = moment(endDateTemp, "YYYY-MM-DD").add(-(size - 1), 'days').format();
                    dateArr = toolUtil.getArrayDateByStartEndDateMin(startDateTemp, endDateTemp);
                }
            }
        }
    } else {
        var msg = {"message": '开始日期或结束日期不能为空!'};
        return callback(msg, null);
    }
    var dayCounts = [];
    async.series([
        // 分页
        function (callbackInner) {
            var temp = {count: dateArrCount, page: Math.ceil(dateArrCount/(size ? size : 1))};
            callbackInner(null, temp);
        },
        function (callbackInner) {
            async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
                startDate = moment(tempDate, "YYYY-MM-DD").format();
                endDate = moment(startDate, "YYYY-MM-DD").add(1, "days").format();
                async.parallelLimit([
                    // 已成团订单总数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {
                                "order_time": {$gte: new Date(startDate), $lt: new Date(endDate)},
                                "newGroupOrderStatus": "0",
                                "isValid": true
                            }},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, groupOrderRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var groupOrderCount = 0;
                                if (groupOrderRes != null && groupOrderRes.length > 0) {
                                    groupOrderCount = groupOrderRes[0].count;
                                }
                                callbackInnerInner(null, groupOrderCount);
                            }
                        });
                        // mtOrder.aggregate({
                        //     "newGroupOrderStatus": "0",
                        //     "isValid": true,
                        //     "order_time": {$gte: startDate, $lt: endDate}
                        //     // timeOption
                        // }, function (err, groupOrderRes) {
                        //     if (err) {
                        //         callbackInnerInner(err, null);
                        //     } else {
                        //         callbackInnerInner(null, groupOrderRes);
                        //     }
                        // });
                    },
                    // 已退款订单总数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {"order_time": {$gte: new Date(startDate), $lt: new Date(endDate)}}},
                            {$match: {"status": "100"}},
                            {$match: {"isValid": true}},
                            {$group: {"_id": {"orderId": "$order_id"}, count: {$sum: 1}}},
                            {$group: {"_id": "$orderId", count: {$sum: 1}}},
                            {$project: {"_id": 0, "count": 1}}
                        ], function (err, refundRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var refundCount = 0;
                                if (refundRes != null && refundRes.length > 0) {
                                    refundCount = refundRes[0].count;
                                }
                                callbackInnerInner(null, refundCount);
                            }
                        });
                        // mtOrder.count({
                        //     "status": "100",
                        //     "isValid": true,
                        //     "order_time": {$gte: startDate, $lt: endDate}
                        //     // timeOption
                        // }, function (err, refundRes) {
                        //     if (err) {
                        //         callbackInnerInner(err, null);
                        //     } else {
                        //         callbackInnerInner(null, refundRes);
                        //     }
                        // });
                    },
                    // 订单佣金总数
                    function (callbackInnerInner) {
                        mtOrder.aggregate([
                            {$match: {
                                "order_time": {$gte: new Date(startDate), $lt: new Date(endDate)},
                                "status": {$ne: "100"},
                                "isValid": true
                            }},
                            {$group: {"_id": {
                                "orderId": "$order_id",
                                "communityCommissionUser": "$communityCommissionUser",
                                "communityCommission": "$communityCommission",
                                "selfPurchaseUser": "$selfPurchaseUser",
                                "selfPurchase": "$selfPurchase",
                                "inviterCommissionUser": "$inviterCommissionUser",
                                "inviterCommission": "$inviterCommission",
                                "shareCommissionUser": "$shareCommissionUser",
                                "shareCommission": "$shareCommission"
                            }, count: {$sum: 1}}}
                        ]).exec(function (err, commTotalRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                var commissionCounts = 0;
                                if (commTotalRes != null && commTotalRes.length > 0) {
                                    for (var i = 0, length = commTotalRes.length; i < length; i++) {
                                        if (commTotalRes[i]._id.shareCommission) {
                                            // 分享订单佣金
                                            commissionCounts += commTotalRes[i]._id.shareCommission;
                                        }
                                        if (commTotalRes[i]._id.selfPurchase) {
                                            // 自购订单佣金
                                            commissionCounts += commTotalRes[i]._id.selfPurchase;
                                        }
                                        if (commTotalRes[i]._id.communityCommission) {
                                            // 小区订单佣金
                                            commissionCounts += commTotalRes[i]._id.communityCommission;
                                        }
                                        if (commTotalRes[i]._id.inviterCommission) {
                                            // 被邀请大使订单佣金
                                            commissionCounts += commTotalRes[i]._id.inviterCommission;
                                        }
                                    }
                                }
                                callbackInnerInner(null, commissionCounts.toFixed(2));
                            }
                        });
                    },
                    // 帖子发布总数
                    function (callbackInnerInner) {
                        Question.count({
                            "category": {$in: ["question", "share"]},
                            "isValid": true,
                            "dateCreated": {$gte: startDate, $lt: endDate}
                        }, function (err, questionRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                callbackInnerInner(null, questionRes);
                            }
                        });
                    },
                    // 闲置发布总数
                    function (callbackInnerInner) {
                        Goods.count({
                            // dateOption
                            "isValid": true,
                            "dateCreated": {$gte: startDate, $lt: endDate}
                        }, function (err, goodsRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                callbackInnerInner(null, goodsRes);
                            }
                        });
                    },
                    // 邀请用户总数
                    function (callbackInnerInner) {
                        UserInvitation.count({
                            // dateOption
                            "dateCreated": {$gte: startDate, $lt: endDate}
                        }, function (err, invitedRes) {
                            if (err) {
                                callbackInnerInner(err, null);
                            } else {
                                callbackInnerInner(null, invitedRes);
                            }
                        });
                    },
                ], parallelLimitCount, function (err, results) {
                    var tempDayCount = {};
                    // 订单总佣金统计日期
                    tempDayCount.orderCountDate = startDate.toString().substr(0, 10);
                    // 已成团订单总数
                    tempDayCount.groupOrders = results[0];
                    // 已退款订单总数
                    tempDayCount.refundOrders = results[1];
                    // 订单总佣金
                    tempDayCount.commissionAll = results[2];
                    // 帖子发布总数
                    tempDayCount.postPushCounts = results[3];
                    // 闲置发布总数
                    tempDayCount.goodsPushCounts = results[4];
                    // 邀请用户总数
                    tempDayCount.invitedUsers = results[5];

                    dayCounts.push(tempDayCount);
                    callbackTempInner(false);
                });
            }, function (err) {
                callbackInner(false);
            });
        },
    ], function (err, orderResults) {
        if (err) {
            callback(err, null);
        } else {
            orderResults[1] = dayCounts;
            callback(null, orderResults);
        }
    });
};